<template>
  <!-- 采购单 在线报价 -->
  <div
    class="procurementOnlineQuotation"
    v-if="info"
  >
    <!-- 验证密码 -->
    <div
      v-if="isCheckPassword"
      class="g-con"
    >
      <div class="checkPassword flexcc-col">
        <div class="">{{ t('DockOrderOnlineQuotation.t1') }}</div>
        <el-form
          ref="checkPasswordFormEl"
          :model="checkPasswordFormData"
          :rules="checkPasswordRules"
          status-icon
          label-position="left"
          class="wp-100"
          @submit.prevent="handleCheckPassword"
        >
          <el-form-item
            label=""
            prop="accessPassword"
          >
            <el-input
              type="password"
              v-model.trim="checkPasswordFormData.accessPassword"
              class="mt-2"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          class="mt-4"
          @click="handleCheckPassword"
        >
          {{ t('confirmText') }}
        </el-button>
      </div>
    </div>

    <!-- 密码验证通过 -->
    <div
      v-if="isValidPassword"
      class="g-con"
    >
      <el-form
        ref="formEl"
        :model="formData"
        :rules="rules"
        label-width="120px"
        status-icon
        label-position="left"
        label-suffix="："
      >
        <div class="header flexsb">
          <div class="flexsc">{{ t('ProcurementOnlineQuotation.l2') }}: {{ info.procureShowInfoVo.orderNo }}</div>
          <div class="flexsc">{{ t('ProcurementOnlineQuotation.l2_1') }}: {{ info.procureShowInfoVo.procureOrderName }}</div>

          <div
            class="flexec"
            v-if="type === 'add'"
          >
            <el-button
              type="primary"
              @click="handleSave"
            >
              {{ t('save') }}
            </el-button>
            <el-button
              v-if="isAdmin"
              type="primary"
              @click="hanldleSubmit"
            >
              {{ t('DockOrderOnlineQuotation.t6') }}
            </el-button>
          </div>
          <div
            class="flexec"
            v-if="type === 'detail'"
          >
            <el-button @click="handleExport"> {{ t('export') }} </el-button>
            <el-button @click="handelSendMsg">
              {{ t('DockOrderOnlineQuotation.t7') }}
            </el-button>
            <el-button
              v-if="info.status === '4' && info.canConfirmQuota"
              type="primary"
              @click="handleConfirmBid"
            >
              {{ t('DockOrderOnlineQuotation.t8') }}
            </el-button>
          </div>
        </div>

        <div class="info flexsb mt-3">
          <div class="flexsc nowrap">
            {{ t('DockOrderOnlineQuotation.t2') }}：
            <el-input
              v-if="type === 'add'"
              v-model.trim="formData.quotationNo"
              :placeholder="t('DockOrderOnlineQuotation.t3')"
              style="width: 400px"
            ></el-input>
            <div v-if="type === 'detail'">{{ formData.quotationNo }}</div>
          </div>
          <div class="flexsc">{{ t('dockRepair.label3') }}: {{ getDictLabel('currency', info.procureShowInfoVo.quoteOrderCurrency) }}</div>
          <div class="flexsc">{{ t('DockOrderOnlineQuotation.t4') }}: {{ dateFormat(info.procureShowInfoVo.quotationEndTime) }}</div>
        </div>

        <div class="info mt-3">
          <div class="tit">{{ t('DockOrderOnlineQuotation.t9') }}</div>
          <div class="con mt-2">
            <el-form-item
              :label="t('ProcurementOnlineQuotation.l1')"
              prop="quotationDescription"
            >
              <el-input
                v-if="type === 'add'"
                type="textarea"
                v-model="formData.quotationDescription"
              />
              <div v-if="type === 'detail'">{{ formData.quotationDescription }}</div>
            </el-form-item>
          </div>
        </div>
      </el-form>

      <div class="info mt-3">
        <div class="tit">{{ t('ProcurementOnlineQuotation.l3') }}</div>
        <div class="con mt-2">
          {{ info.procureShowInfoVo.procureStatement }}
        </div>
      </div>

      <div class="info mt-3">
        <div class="tit">{{ t('procurement.step2page.form.l2') }}</div>
        <div class="con mt-2">{{ info.procureQuotationDetailList[0]?.projectName }}</div>
      </div>

      <!-- 场景一 -->
      <ShippingInfo
        v-if="info.shcwShippingVo"
        :data="info.shcwShippingVo"
      />

      <!-- 场景二 -->
      <div
        v-else
        class="info mt-3"
      >
        <div class="tit">{{ t('ProcurementOnlineQuotation.t1') }}</div>
        <div class="con mt-2">
          <div>{{ t('ProcurementOnlineQuotation.l4') }}: {{ info.procureShowInfoVo.shipRepairYardName }}</div>
          <div>{{ t('ProcurementOnlineQuotation.l5') }}: {{ info.procureShowInfoVo.repairYardCountries }}</div>
          <div>{{ t('ProcurementOnlineQuotation.l6') }}: {{ info.procureShowInfoVo.repairYardArea }}</div>
        </div>
      </div>

      <!--  -->
      <div class="info mt-3">
        <div class="table">
          <el-auto-resizer>
            <template #default="{ height, width }">
              <el-table-v2
                :columns="columns"
                :data="tableData"
                :width="width"
                :height="height"
                fixed
              >
                <template #row="props">
                  <Row v-bind="props" />
                </template>
              </el-table-v2>
            </template>
          </el-auto-resizer>
        </div>
      </div>

      <div class="info mt-3">
        <div class="tit">{{ t('attachments') }}</div>
        <div
          class="con mt-2"
          v-if="type === 'add'"
        >
          <Uploads
            ref="UploadsRef"
            @change="fileChange"
            :tip="t('Uploads.t2')"
          />
        </div>

        <div
          class="con mt-2"
          v-if="type === 'detail'"
        >
          <div
            v-for="(item, index) in info.urlList"
            :key="index"
          >
            <a
              :href="item.url"
              target="_blank"
            >
              {{ item.file_name }}
            </a>
          </div>
        </div>
      </div>
    </div>

    <!-- 设置访问密码 -->
    <AccessPassword
      v-if="dialogAccessPassword"
      :visible="dialogAccessPassword"
      @close="dialogAccessPassword = false"
      @setAccessPassword="setAccessPassword"
    />

    <!-- 确认中标 -->
    <ConfirmBid
      v-if="dialogConfirmBid"
      :visible="dialogConfirmBid"
      :objId="editId"
      type="procurement"
      @close="dialogConfirmBid = false"
      @getList="getDetail"
    />

    <!-- 提交确认 -->
    <Confirm
      v-if="submitConfirmDialog"
      :visible="submitConfirmDialog"
      :text="t('DockOrderOnlineQuotation.c1')"
      @close="submitConfirmDialog = false"
      @cancel="submitConfirmDialog = false"
      @confirm="submitConfirmFn"
    />
  </div>
</template>

<script setup lang="jsx">
import { ref, reactive, onBeforeMount, watch, unref, computed, nextTick, cloneVNode } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { viewBeforeApi, queryQuotationByIdApi, viewOuotationApi, saveQuotationApi, submitQuotationApi, updateQuotoDetailApi, exportProcureQuoteApi } from '@/service/procurement'
import { dateFormat, download, amountFormat } from '@/utils/index'
import { uploads } from '@/service/common'
import Decimal from 'decimal.js'
import moment from 'moment'
import useLogin from '@/stores/login'
import useDialogue from '@/stores/dialogue'
import { debounce } from 'lodash'

import AccessPassword from '@/views/userCenter/AccessPassword.vue'
import Uploads from '@/components/Uploads.vue'
import ConfirmBid from '../shipowner/ConfirmBid.vue'
import Confirm from '@/components/Confirm.vue'

import useDict from '@/hooks/useDict'
const { dictData, getDictData, getDictLabel } = useDict()

onBeforeMount(() => {
  init()
})

const { t, locale } = useI18n()
watch(locale, () => {
  init()
})

const router = useRouter()
const route = useRoute()
const storeLogin = useLogin()

const storeDialogue = useDialogue()
const { setDialogVisible, setActivePerson } = storeDialogue

const id = route.query.id
const type = computed(()=>{
  let res = 'detail'

  // 采购服务商 && 报价员
  if (storeLogin.userInfo.registerClassCode === 'cgfws' && storeLogin?.userInfo?.id == route.query.quotaCreateBy) {
    res = 'add'
  }


  return res
})
const isShipownerView = ref(['wxxqf', 'wxfws'].includes(storeLogin.userInfo.registerClassCode)) // 船东船管/修船厂查看报价

// 是否是管理员
const isAdmin = computed(() => {
  return storeLogin?.userInfo?.isAdmin === '1'
})

// 导出
const handleExport = () => {
  exportProcureQuoteApi({ quotationId: id }).then((res) => {
    download(res)
  })
}

// 保存报价单
const saveSubmit = async () => {
  const params = {
    id,
    ...formData.value
  }

  params.urlList = await handleUpload()

  saveQuotationApi(params).then(({ msg }) => {
    ElMessage.success(msg)
    getDetail()
  })
}
const handleSave = () => {
  const data = unref(tableData.value)
  if (data.some((item) => !item.isSave)) {
    ElMessage.warning(t('DockOrderOnlineQuotation.w1'))
    return
  }

  if (!formEl.value) return
  formEl.value.validate(async (valid, fields) => {
    if (valid) {
      // 如果未设置密码
      if (!info.value.accessPassword) {
        dialogAccessPassword.value = true
        return
      }
      saveSubmit()
    }
  })
}

// 提交报价单
const submitConfirmDialog = ref(false)
const hanldleSubmit = () => {
  if (!formData.value.quotationNo) {
    ElMessage.warning(t('ProcurementOnlineQuotation.w1'))
    return
  }

  const data = unref(tableData.value)
  if (data.some((item) => !item.isSave)) {
    ElMessage.warning(t('DockOrderOnlineQuotation.w1'))
    return
  }

  if (!formEl.value) return
  formEl.value.validate((valid, fields) => {
    if (valid) {
      // 如果未设置密码
      if (!info.value.accessPassword) {
        dialogAccessPassword.value = true
        return
      }
      submitConfirmDialog.value = true
    }
  })
}
const submitConfirmFn = () => {
  submitQuotationApi({
    id,
    ...formData.value
  }).then(({ msg }) => {
    ElMessage.success(msg)
    submitConfirmDialog.value = false
    router.go(-1)
  })
}

// 发消息
const handelSendMsg = () => {
  const activePerson = {
    // 修船厂给采购服务商发
    wxfws: {
      customerName: info.value.quotaCreateByName,
      customerId: info.value.quotaCreateBy
    },
    // 船东船管给采购服务商发
    wxxqf: {
      customerName: info.value.quotaCreateByName,
      customerId: info.value.quotaCreateBy
    },
    // 采购服务商给创建人(船东船管、修船厂)发
    cgfws: {
      customerName: info.value.procureShowInfoVo.createByName,
      customerId: info.value.procureShowInfoVo.createBy
    }
  }
  setDialogVisible(true)
  setActivePerson(activePerson[storeLogin.userInfo.registerClassCode])
}

// 正在操作的id
const editId = ref(null)

// 确认中标
const dialogConfirmBid = ref(false)
const handleConfirmBid = (item) => {
  dialogConfirmBid.value = true
  editId.value = id
}

// 表单
const formEl = ref(null)
const formData = ref({
  quotationImportList: []
})
const rules = ref({
  quotationDescription: [{ required: true, message: t('ProcurementOnlineQuotation.r1'), trigger: 'change' }]
})

// 访问密码 弹窗
const dialogAccessPassword = ref(false)
// 设置访问密码
const setAccessPassword = (val) => {
  formData.value.accessPassword = val
  saveSubmit()
}

// 验证密码
const checkPasswordFormEl = ref(null)
const checkPasswordFormData = ref({})
const checkPasswordRules = {
  accessPassword: [{ required: true, message: t('DockOrderOnlineQuotation.t47'), trigger: 'change' }]
}
const isExpired = ref(false) // 超过报价单截止日期
// 是否需要密码验证
const isCheckPassword = computed(() => {
  // 如果逾期 或 无密码 或 已开标
  if (isExpired.value || !info.value.accessPassword || info.value.status === '2') {
    isValidPassword.value = true
    return false
  }
  // 有密码 && 密码未通过
  return info.value.accessPassword && !isValidPassword.value
})
const isValidPassword = ref(false) // 密码是否验证通过
const handleCheckPassword = () => {
  if (!checkPasswordFormEl.value) return
  checkPasswordFormEl.value.validate((valid, fields) => {
    if (valid) {
      viewBeforeApi({
        id,
        ...checkPasswordFormData.value
      }).then(() => {
        isValidPassword.value = true
        getDetail()
      })
    }
  })
}

// 报价单详情
const info = ref(null)
const getDetail = async () => {
  let apiFun = queryQuotationByIdApi

  if (isShipownerView.value) {
    apiFun = viewOuotationApi
  }

  await apiFun({ quotationId: id }).then(({ data }) => {
    info.value = data

    const { procureShowInfoVo, quotationNo, quotationDescription, procureQuotationDetailList, urlList } = data

    isExpired.value = Number(moment().format('X')) > Number(procureShowInfoVo.quotationEndTime) // 今天大于截止日期 为逾期

    if (urlList) {
      fileList.value = urlList.map((item) => {
        return {
          name: item.file_name,
          url: item.url
        }
      })
    }

    if (type.value === 'add') {
      nextTick(() => {
        if (UploadsRef.value) {
          UploadsRef.value.setFileList(fileList.value)
        }
      })
    }

    // 表单回显
    formData.value = {
      quotationNo,
      quotationDescription
    }

    // 采购单明细
    if (procureQuotationDetailList) {
      procureQuotationDetailList.forEach((item) => {
        item.isSave = true
      })
      tableData.value = procureQuotationDetailList
    }
  })
}

// 表格 列
const columns = ref([])
const tableData = ref([])

const Row = ({ rowData, rowIndex, cells, columns }) => {
  // console.log(rowData, rowIndex, cells, columns)

  const style = {
    backgroundColor: '#F8CD95'
  }

  const fn = (key) => {
    const index = columns.findIndex((item) => item.dataKey === key)
    if (index !== -1) {
      cells[index] = cloneVNode(cells[index], { style })
    }
  }

  if (rowData.modifyOrNotPrice === 1) {
    fn('price')
  }
  if (rowData.modifyOrNotDiscount === 1) {
    fn('discount')
  }
  if (rowData.modifyOrNotAmount === 1) {
    fn('amount')
  }
  if (rowData.modifyOrNotQuotaRemark === 1) {
    fn('quotaRemark')
  }

  return cells
}

const getColumns = () => {
  const setRef = (el) => {
    if (el) {
      el.focus?.()
    }
  }

  const editingClassName = { 'table-v2-inline-editing-trigger': type.value === 'add' }

  // 保存
  const handleRowSave = debounce(
    (rowData) => {
      const { id, price, discount, amount, quotaRemark } = rowData
      updateQuotoDetailApi({ id, price, discount, amount, quotaRemark }).then(({ msg }) => {
        ElMessage.success(msg)
        rowData.isSave = true
        rowData.editingKey = null
      })
    },
    500,
    {
      leading: true, // 延长开始后调用
      trailing: false // 延长结束前调用
    }
  )

  // 回车保存
  const handleEnterSave = (e, rowData) => {
    if (['Enter', 'NumpadEnter'].includes(e.code)) {
      handleRowSave(rowData)
    }
  }

  columns.value = [
    {
      title: t('indexNumber'),
      key: 'index',
      dataKey: 'index',
      width: 50,
      cellRenderer: ({ rowIndex }) => {
        return rowIndex + 1
      }
    },
    {
      title: t('procurement.ProjectAdd.l2_1'),
      key: 'projectName',
      dataKey: 'projectName',
      width: 150
    },
    {
      title: t('procurement.ProjectAdd.l3_1'),
      key: 'procureNo',
      dataKey: 'procureNo',
      width: 150
    },
    {
      title: t('procurement.ProjectAdd.l11'),
      key: 'drawingNumber',
      dataKey: 'drawingNumber',
      width: 100
    },
    {
      title: t('procurement.category1Col.tit5'),
      key: 'procureSpec',
      dataKey: 'procureSpec',
      width: 80
    },
    // {
    //   title: t('procurement.col.t2'),
    //   key: 'procureModel',
    //   dataKey: 'procureModel',
    //   width: 100
    // },
    {
      title: t('procurement.col.t3'),
      key: 'unit',
      dataKey: 'unit',
      width: 80
    },
    {
      title: t('procurement.category4Col.tit5'),
      key: 'requireCount',
      dataKey: 'requireCount',
      width: 80
    },
    {
      title: t('procurement.category2Col.tit8'),
      key: 'remark',
      dataKey: 'remark',
      width: 100
    },
    {
      title: t('userCenter.price'), //
      key: 'price',
      dataKey: 'price',
      width: 100,
      cellRenderer: ({ rowData, rowIndex }) => {
        watch(
          () => rowData.price,
          (newVal) => {
            if (!newVal) return
            const { requireCount, discount } = rowData
            // activeItem.amount = requireCount * newVal * (1 - discount * 0.01)
            rowData.amount = Number(
              Decimal(requireCount || 0)
                .mul(Decimal(newVal || 0))
                .mul(Decimal(1).sub(Decimal(discount || 0).mul(0.01)))
            )
          }
        )

        if (rowData.editingKey === 'price') {
          return (
            <el-input-number
              ref={setRef}
              v-model={rowData.price}
              controls={false}
              min={0}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          if (type.value === 'add') {
            rowData.editingKey = 'price'
          }
        }

        return (
          <div
            class={editingClassName}
            onClick={onEnterEditMode}
          >
            {amountFormat(rowData.price)}
          </div>
        )
      }
    },
    {
      title: t('userCenter.discount'), //
      key: 'discount',
      dataKey: 'discount',
      width: 100,
      hidden: info.value.procureShowInfoVo.quoteOrderCurrency === 'currency_0', // 币种为'人民币'时隐藏
      cellRenderer: ({ rowData, rowIndex }) => {
        if (rowData.editingKey === 'discount') {
          return (
            <el-input-number
              ref={setRef}
              v-model={rowData.discount}
              controls={false}
              min={0}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          if (type.value === 'add') {
            rowData.editingKey = 'discount'
          }
        }

        return (
          <div
            class={editingClassName}
            onClick={onEnterEditMode}
          >
            {rowData.discount !== null ? `${rowData.discount}%` : ''}
          </div>
        )
      }
    },
    {
      title: t('userCenter.amount'), //
      key: 'amount',
      dataKey: 'amount',
      width: 100,
      cellRenderer: ({ rowData, rowIndex }) => {
        if (rowData.editingKey === 'amount') {
          return (
            <el-input-number
              ref={setRef}
              v-model={rowData.amount}
              controls={false}
              min={0}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          if (type.value === 'add') {
            rowData.editingKey = 'amount'
          }
        }

        return (
          <div
            class={editingClassName}
            onClick={onEnterEditMode}
          >
            {amountFormat(rowData.amount)}
          </div>
        )
      }
    },
    {
      title: t('userCenter.remark'), //
      key: 'quotaRemark',
      dataKey: 'quotaRemark',
      width: 220,
      cellRenderer: ({ rowData, rowIndex }) => {
        if (rowData.editingKey === 'quotaRemark') {
          return (
            <el-input
              ref={setRef}
              v-model={rowData.quotaRemark}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          if (type.value === 'add') {
            rowData.editingKey = 'quotaRemark'
          }
        }
        return (
          <div
            class={editingClassName}
            onClick={onEnterEditMode}
          >
            {rowData.quotaRemark}
          </div>
        )
      }
    }
  ]

  if (type.value === 'add') {
    return
    columns.value.push({
      title: t('dockRepair.coltit6'), // 操作
      width: 100,
      fixed: 'right',
      cellRenderer: ({ rowData, rowIndex }) => {
        // 保存
        const handleRowSave = () => {
          const { id, price, discount, amount, quotaRemark } = rowData
          updateQuotoDetailApi({ id, price, discount, amount, quotaRemark }).then(({ msg }) => {
            ElMessage.success(msg)
            rowData.isSave = true
          })
        }

        // 编辑
        const handleRowEdit = (value) => {
          rowData.isSave = false
        }

        return (
          <>
            {rowData.isSave ? (
              <img
                src={new URL('@/assets/img/icon_bianji.png', import.meta.url)}
                height="22"
                class="mr-2"
                onClick={handleRowEdit}
              />
            ) : (
              <img
                src={new URL('@/assets/img/icon_baocun.png', import.meta.url)}
                height="22"
                class="mr-2"
                onClick={handleRowSave}
              />
            )}
          </>
        )
      }
    })
  }
}

// 文件列表
const fileList = ref([])
const fileChange = (val) => {
  fileList.value = val
}
const UploadsRef = ref(null)
const handleUpload = () => {
  return new Promise((resolve, reject) => {
    const newList = fileList.value.filter((item) => item.raw)
    const oldList = fileList.value.filter((item) => !item.raw).map((item) => {
      return {
        url: item.url,
        name:  item.name
      }
    })

    if (newList.length) {
      const formData = new FormData()
      newList.forEach((item) => {
        formData.append('files', item.raw)
      })
      uploads(formData).then(({ urls, fileNames }) => {
        const newUrls = urls.split(',')
        fileList.value = newUrls.map((newUrl, newUrlIndex) => {
          return {
            name: fileNames.split(',')[newUrlIndex],
            url: newUrl
          }
        })
        UploadsRef.value.setFileList(fileList.value)
        resolve([...oldList, ...newUrls.map((url, index)=>{
          return {
            url,
            name: fileNames.split(',')[index]
          }
        })])
      })
    } else {
      resolve(oldList)
    }
  })
}

//
const init = async () => {
  getDictData('currency')
  getDictData('ships_type')
  getDictData('classification_society')
  await getDetail()
  getColumns()
}
</script>

<style scoped lang="scss">
.procurementOnlineQuotation {
  background: #f5f5f5;
  padding: 30px 0;
  margin-bottom: -76px;

  .el-button {
    min-width: 140px;
  }
  .addbtn {
    color: var(--mainColor);
    cursor: pointer;
  }

  .checkPassword {
    padding: 100px 400px;
  }

  .header {
  }

  .info {
    background: #fff;
    padding: 24px;
    > .tit {
      border-bottom: 2px solid #252628;
      font-weight: bold;
      padding: 10px 0;
    }
  }

  .table {
    border-top: 2px solid #252628;
    height: 700px;

    :deep(.table-v2-inline-editing-trigger) {
      border: 1px transparent dotted;
      padding: 4px;
      min-height: 26px;
      min-width: 100%;
      cursor: text;
      border-radius: 3px;
    }

    :deep(.table-v2-inline-editing-trigger:hover) {
      border-color: var(--el-color-primary);
    }

    :deep(.el-table-v2__header-cell) {
      background: #f0f3f8;
      color: #252628;
    }
    :deep(.no-save) {
      background: #f9ecd9;
    }
  }

  :deep(.el-input-number .el-input__inner) {
    text-align: left;
  }
}
</style>
